package handler

import (
	"github.com/gin-gonic/gin"
	"info-hub/model"
	"info-hub/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	if tel == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.User{
		Tel:      tel,
		Password: pkg.Md5str1(password),
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.News{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.News{}).Count(&count)
	var news model.News
	err := model.DB.Offset(offset).Limit(size).Find(&news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"data":  &news,
			},
		})
		return
	}

}
